﻿using FolderSelect;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MangaReader
{

    public partial class Form1 : Form
    {

        string store1, store2, store3, store4;
        //MODIFIED--------------------------
        bool color = true;
        string lastPath;

        public Form1(string[] path)
        {
            InitializeComponent();
            getData();
            if (path != null && path.Length > 0)
            {
                createReader(System.IO.Path.GetFullPath(path[0]));
            }
        }

        public void createReader(String path)
        {
            //MODIFIED-------------------------------------
            try
            {
                lastPath = path;
                setData();
                List<String> files, folders, top;
                String code = "", code1 = "", code2 = "";
                top = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly).ToList();

                code1 += "    changeBg(" + color.ToString().ToLower() + ");" + Environment.NewLine;
                store1 = txtOpenChaptersList.Text.ToString().ToLower();
                code2 += "    bindHotkeys('c', \"" + store1 + "\"); " + Environment.NewLine;
                store2 = txtOpenSettings.Text.ToString().ToLower();
                code2 += "    bindHotkeys('m', \"" + store2 + "\"); " + Environment.NewLine;
                store3 = txtGoPrevChap.Text.ToString().ToLower();
                code2 += "    bindHotkeys('p', \"" + store3 + "\"); " + Environment.NewLine;
                store4 = txtGoNextChap.Text.ToString().ToLower();
                code2 += "    bindHotkeys('n', \"" + store4 + "\"); " + Environment.NewLine;

                code += "    display(\"";
                files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                String o = convert(path);
                code += "<div name='" + o.Substring(o.LastIndexOf('/') + 1).Replace("'", "&apos;") + "'>";
                files = convert(files);
                foreach (String x in files)
                {
                    code += "<input value='" + x.Replace("'", "&apos;") + "'/>";
                }
                code += "</div>";
                foreach (String t in top)
                {
                    files = Directory.GetFiles(t, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                    String f = convert(t);
                    code += "<div name='" + f.Substring(f.LastIndexOf('/') + 1).Replace("'", "&apos;") + "'>";
                    files = convert(files);
                    foreach (String s in files)
                    {
                        code += "<input value='" + s.Replace("'", "&apos;") + "'/>";
                    }
                    code += "</div>";
                    folders = Directory.GetDirectories(t, "*", SearchOption.TopDirectoryOnly).ToList();
                    foreach (String c in folders)
                    {
                        files = Directory.GetFiles(c, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                        String a = convert(c);
                        code += "<div name='" + a.Substring(a.LastIndexOf('/') + 1).Replace("'", "&apos;") + "'>";
                        files = convert(files);
                        foreach (String v in files)
                        {
                            code += "<input value='" + v.Replace("'", "&apos;") + "'/>";
                        }
                        code += "</div>";
                    }
                    code += "</div>";
                }
                code += "</div>\");";

                String[] header, body1, body2;

                header = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\header.txt");
                System.IO.File.WriteAllLines(Application.StartupPath + @"\reader.html", header);
                if (color)
                {
                    body1 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\BlackMenu.txt");
                    System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body1);
                }
                else
                {
                    body1 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\WhiteMenu.txt");
                    System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body1);
                }
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code1 + Environment.NewLine);
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code2 + Environment.NewLine);
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code + Environment.NewLine);
                body2 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\body2.txt");
                System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body2);
                System.Diagnostics.Process.Start(Application.StartupPath + @"\reader.html");
            }
            catch (Exception exc)
            {
                //MODIFIED------------------------------------------
                MessageBox.Show("Import failded. " + exc.Message + ". Please restart or redownload the program.");
            }
        }

        public List<String> convert(List<String> s)
        {
            List<String> e = new List<string>();
            foreach(String t in s)
            {
            Uri u = new System.Uri(t);
            e.Add(u.AbsoluteUri);
            }
            return e;
        }

        public String convert(String s)
        {
            Uri u = new System.Uri(s);
            return u.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
                if (radioButtonBlack.Checked)
                {
                    color = true;
                }
                string startupPath = Application.StartupPath;
                using (FolderBrowserDialog dialog = new FolderBrowserDialog())
                {
                    var fsd = new FolderSelectDialog();
                    //MODIFIED----------------------------------------
                    fsd.Title = "Select a Folder";
                    fsd.InitialDirectory = lastPath;

                    if (fsd.ShowDialog(IntPtr.Zero))
                    {
                        createReader(fsd.FileName);
                    }
                }
            
            
        }

        private void txtOpenChaptersList_KeyPress(object sender, KeyPressEventArgs e)
        {
            //MODIFIED---------------------------------
            e.KeyChar = Char.ToUpper(e.KeyChar); 
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                //MODIFIED----------------------------------------
                MessageBox.Show("Value must be from A-Z.");

            }
            else if (e.KeyChar.ToString() == txtOpenSettings.Text.ToString() || e.KeyChar.ToString() == txtGoNextChap.Text.ToString() || e.KeyChar.ToString() == txtGoPrevChap.Text.ToString())
            {
                e.Handled = true;
                //MODIFIED----------------------------------------
                MessageBox.Show("Hotkeys must be unique from one another.");
            }
            else 
            {
                txtOpenChaptersList.Clear();
            }
        }

        private void txtOpenSettings_KeyPress(object sender, KeyPressEventArgs e)
        {
            //MODIFIED---------------------------------
            e.KeyChar = Char.ToUpper(e.KeyChar); 
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Value must be from A-Z.");

            }
            else if (e.KeyChar.ToString() == txtOpenChaptersList.Text.ToString() || e.KeyChar.ToString() == txtGoNextChap.Text.ToString() || e.KeyChar.ToString() == txtGoPrevChap.Text.ToString())
            {
                e.Handled = true;
                MessageBox.Show("Hotkeys must be unique from one another.");
            }
            else 
            {
                txtOpenSettings.Clear();
            }
        }

        private void txtGoPrevChap_KeyPress(object sender, KeyPressEventArgs e)
        {
            //MODIFIED---------------------------------
            e.KeyChar = Char.ToUpper(e.KeyChar); 
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Value must be from A-Z.");

            }
            else if (e.KeyChar.ToString() == txtOpenSettings.Text.ToString() || e.KeyChar.ToString() == txtOpenChaptersList.Text.ToString() || e.KeyChar.ToString() == txtGoNextChap.Text.ToString())
            {
                e.Handled = true;
                MessageBox.Show("Hotkeys must be unique from one another.");
            }
            else 
            {
                txtGoPrevChap.Clear();
            }
        }

        private void txtGoNextChap_KeyPress(object sender, KeyPressEventArgs e)
        {
            //MODIFIED---------------------------------
            e.KeyChar = Char.ToUpper(e.KeyChar); 
            char ch = e.KeyChar;
            if (!Char.IsLetter(ch))
            {
                e.Handled = true;
                MessageBox.Show("Value must be from A-Z.");

            }
            else if (e.KeyChar.ToString() == txtOpenSettings.Text.ToString() || e.KeyChar.ToString() == txtOpenChaptersList.Text.ToString() || e.KeyChar.ToString() == txtGoPrevChap.Text.ToString())
            {
                e.Handled = true;
                MessageBox.Show("Hotkeys must be unique from one another.");
            }
            else 
            {
                txtGoNextChap.Clear();
            }
        }

        private void radioButtonBlack_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonBlack.Checked)
            {
                color = true;
            }
        }

        private void radioButtonWhite_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWhite.Checked)
            {
                color = false;
            }
        }

        private void btnLastChoice_Click(object sender, EventArgs e)
        {
            try
            {
                List<String> files, folders, top;
                String code = "", code1 = "", code2 = "";

                top = Directory.GetDirectories(lastPath, "*", SearchOption.TopDirectoryOnly).ToList();
                code1 += "changeBg(" + color.ToString().ToLower() + ");";
                store1 = txtOpenChaptersList.Text.ToString().ToLower();
                code2 += "bindHotkeys('c', \"" + store1 + "\"); ";
                store2 = txtOpenSettings.Text.ToString().ToLower();
                code2 += "bindHotkeys('m', \"" + store2 + "\"); ";
                store3 = txtGoPrevChap.Text.ToString().ToLower();
                code2 += "bindHotkeys('p', \"" + store3 + "\"); ";
                store4 = txtGoNextChap.Text.ToString().ToLower();
                code2 += "bindHotkeys('n', \"" + store4 + "\"); ";

                code += "display(\"";
                files = Directory.GetFiles(lastPath, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                String o = convert(lastPath);
                code += "<div name='" + o.Substring(o.LastIndexOf('/') + 1) + "'>";
                files = convert(files);
                foreach (String x in files)
                {
                    code += "<input value='" + x + "'/>";
                }
                code += "</div>";
                foreach (String t in top)
                {
                    files = Directory.GetFiles(t, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                    String f = convert(t);
                    code += "<div name='" + f.Substring(f.LastIndexOf('/') + 1) + "'>";
                    files = convert(files);
                    foreach (String s in files)
                    {
                        code += "<input value='" + s + "'/>";
                    }
                    code += "</div>";
                    folders = Directory.GetDirectories(t, "*", SearchOption.TopDirectoryOnly).ToList();
                    foreach (String c in folders)
                    {
                        files = Directory.GetFiles(c, "*.*", SearchOption.TopDirectoryOnly).Where(file => file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpeg") || file.ToLower().EndsWith("gif") || file.ToLower().EndsWith("bmp") || file.ToLower().EndsWith("thm") || file.ToLower().EndsWith("tif")).ToList();
                        String a = convert(c);
                        code += "<div name='" + a.Substring(a.LastIndexOf('/') + 1) + "'>";
                        files = convert(files);
                        foreach (String v in files)
                        {
                            code += "<input value='" + v + "'/>";
                        }
                        code += "</div>";
                    }
                    code += "</div>";
                }
                code += "</div>\");";

                //MODIFIED-------------------------------------
                String[] header, body1, body2;
                header = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\header.txt");
                System.IO.File.WriteAllLines(Application.StartupPath + @"\reader.html", header);
                if (color)
                {
                    body1 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\BlackMenu.txt");
                    System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body1);
                }
                else
                {
                    body1 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\WhiteMenu.txt");
                    System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body1);
                }
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code1 + Environment.NewLine);
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code2 + Environment.NewLine);
                System.IO.File.AppendAllText(Application.StartupPath + @"\reader.html", code + Environment.NewLine);
                body2 = System.IO.File.ReadAllLines(Application.StartupPath + @"\Resources\body2.txt");
                System.IO.File.AppendAllLines(Application.StartupPath + @"\reader.html", body2);
                System.Diagnostics.Process.Start(Application.StartupPath + @"\reader.html");
            }
            catch
            {
                MessageBox.Show("No recent action found. Please open new folder of manga.");
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            String path, code;
            path = Application.ExecutablePath.Replace(@"\", @"\\");
            code = "Windows Registry Editor Version 5.00" + Environment.NewLine + Environment.NewLine;
            code += "[HKEY_CLASSES_ROOT\\Directory\\shell\\View with MangaReader\\command]" + Environment.NewLine;
            code += "@=\"" + path + " %1\"";
            System.IO.File.WriteAllText("addContext.reg", code);
            System.Diagnostics.Process.Start("addContext.reg");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String path, code;
            path = Application.ExecutablePath.Replace(@"\", @"\\");
            code = "Windows Registry Editor Version 5.00" + Environment.NewLine + Environment.NewLine;
            code += "[-HKEY_CLASSES_ROOT\\Directory\\shell\\View with MangaReader]" + Environment.NewLine;
            System.IO.File.WriteAllText("removeContext.reg", code);
            System.Diagnostics.Process.Start("removeContext.reg");
        }

        //MODIFIED-----------------------------
        private void getData() 
        {
            try
            {
                //Line in order of appearance: lastPath, hotkeys
                String[] tmp = System.IO.File.ReadAllLines(Application.StartupPath + "/Resources/data.txt");
                lastPath = tmp[0];

                Char chapter, setting, prev, next;
                chapter = Char.Parse(tmp[1]);
                setting = Char.Parse(tmp[2]);
                prev = Char.Parse(tmp[3]);
                next = Char.Parse(tmp[4]);

                txtOpenChaptersList.Text = chapter.ToString();
                txtOpenSettings.Text = setting.ToString();
                txtGoPrevChap.Text = prev.ToString();
                txtGoNextChap.Text = next.ToString();
            }
            catch (Exception)
            {
                //File data.txt does not exist or is corrupted. Use default settings
            }
        }

        private void setData()
        {
            try
            {
                //Line in order of appearance: lastPath, isInfEnabled, infDelay, color, hotkeys
                String nl = Environment.NewLine;
                String content = lastPath + nl + txtOpenChaptersList.Text + nl + txtOpenSettings.Text + nl;
                content += txtGoPrevChap.Text + nl + txtGoNextChap.Text;
                System.IO.File.WriteAllText(Application.StartupPath + "/Resources/data.txt", content);
            }
            catch (Exception)
            {
                MessageBox.Show("Error saving data.");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            setData();
        }
    }
}